package xuperchain

import (
	"encoding/json"
	"fmt"
	"strconv"

	"github.com/xuperchain/xuper-sdk-go/v2/account"
	"github.com/xuperchain/xuper-sdk-go/v2/xuper"
)

type fileResponse struct {
	Name     string `json:"0"`
	Abstract string `json:"1"`
}

func GetAllFiles(page int, pageSize int) ([]string, []string) {
	var paperNames []string
	var abstracts []string

	account, err := account.GetAccountFromFile(path, pwd)
	if err != nil {
		fmt.Printf("GetAccountFromFile err: %v\n", err)
		panic(err)
	}

	err = account.SetContractAccount(contractAccount)
	if err != nil {
		panic(err)
	}

	xchainClient, err := xuper.New(nodeAddress)
	if err != nil {
		panic(err)
	}

	contractName := "xc_filestorage8"

	totalFiles := GetFileListLength()

	// 计算起始索引和结束索引
	startIndex := (page - 1) * pageSize
	endIndex := startIndex + pageSize
	if endIndex > totalFiles {
		endIndex = totalFiles
	}

	for i := startIndex; i < endIndex; i++ {
		argsGetFileAtIndex := map[string]string{
			"index": strconv.Itoa(i),
		}
		txgetFileAtIndex, err := xchainClient.QueryEVMContract(account, contractName, "getFileAtIndex", argsGetFileAtIndex)
		if err != nil {
			panic(err)
		}
		var fileResponseArray []fileResponse
		err = json.Unmarshal([]byte(txgetFileAtIndex.ContractResponse.Body), &fileResponseArray)
		if err != nil {
			panic(err)
		}

		// 每次响应包含两个元素：文件名和摘要
		if len(fileResponseArray) == 2 {
			paperNames = append(paperNames, fileResponseArray[0].Name)
			abstracts = append(abstracts, fileResponseArray[1].Abstract)
		}
	}
	return paperNames, abstracts
}
